<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\LogOutStorageModel;
use App\V3\V3_2_7\Models\LogPackageModel;
use App\V3\V3_2_7\Models\MaterielContentModel;
use App\V3\V3_2_7\Models\MaterielModel;
use App\V3\V3_2_7\Models\MaterielsTypeModel;
use App\V3\V3_2_7\Models\SellGoodsDetailModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Models\SellPackageContentModel;
use App\V3\V3_2_7\Models\SellPackageDetailModel;
use App\V3\V3_2_7\Models\SellPayRecordModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use App\V3\V3_2_7\Models\TallyModel;
use App\V3\V3_2_7\Models\MaterielPayHistoryModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\SellGoodsDetail;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_7\Models\SellGoodsListModel;
use App\V3\V3_2_7\Models\SupplierCustomerModel;

class StatisticsService
{
    static public function sell($data, $date, $condition, $condition1)
    {
        $tallyModel = SellGoodsDetail::select(DB::raw("sum(num) as num,image,name,sum((price-cost_price)*num) as profit,sum(price*num) as total_price"))
            ->where($condition)
            ->whereBetween('sell_date',$date)
            ->groupBy('name','type_name')->get();

        $packageInfo = SellPackageDetailModel::select(
            DB::raw("sum(num) as num,sum((price-total_cost)*num) as profit,sum(price*num) as total_price"),
            'b.package_name'
        )
            ->from('sell_package_detail as a')
            ->leftJoin('package as b', 'b.id', '=', 'a.package_id')
            ->with('packageContent', function($query) {
                $query->select(
                    'a.package_detail_id'
                )
                    ->from('sell_package_content as a')
                    ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                    ->leftJoin('materiel_class as c', 'b.id', '=', 'b.parent_id')
                    ->leftJoin('materiel_type as d', 'd.id', '=', 'a.type_id')
                    ->leftJoin('storage as e', 'e.id', '=', 'a.storage_id')
                    ->leftJoin('storage_manage as f', 'f.id', '=', 'a.storage_manage_id');
            })
            ->where($condition1)
            ->whereBetween('sell_date',$date)
            ->groupBy('package_id')->get();
    }

    //采购报表
    static public function statementMateriel($condition, $data, $userInfo)
    {
        $materielInfo = MaterielModel::where([
            'repeal_status' => 0,
            'a.delete_flag' => 0
        ])
            ->from('materiel as a')
            ->where($userInfo)
            ->where(function($query) {
                $query->orWhere('pay_status', '!=', '0')
                    ->orWhere('in_storage_status', '!=', 0);
            })
            ->where($condition)
            ->get()->toArray();

        $materialId = [];//采购单id
        foreach($materielInfo as $materielValue) {
            $materialId[] = $materielValue['id'];
        }

        $amountInfo = MaterielContentModel::selectRaw('
            SUM(num) as total_amount
        ')
            ->from('materiel_content as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where('b.delete_flag', 0)
            ->where(function($query) use($data){
                if(!empty($data['keyword'])){
                    $query->orWhere('b.materiel_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.type_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.materiel_no','like','%'.$data['keyword'].'%');
                }
            });
        if(isset($data['storage_id'])){
            $amountInfo ->where('a.storage_id', $data['storage_id']);
        }
        $amountInfo = $amountInfo->whereIn('materiel_id', $materialId)
            ->groupBy('a.main_id')
            ->first();
        $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];

        $priceInfo = MaterielContentModel::selectRaw('
            SUM(num * unit_price) as total_price
        ')
            ->whereIn('materiel_id', $materialId)
            ->groupBy('main_id')
            ->first();

        $result['total_price'] = empty($priceInfo)?0:$priceInfo['total_price'];

        $conentInfo = MaterielContentModel::select(
            'a.type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            'b.materiel_img',
            DB::raw('SUM(num * unit_price) as total_unit_price'),
            DB::raw('SUM(num) as num')
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where(function($query) use($data){
                if(!empty($data['keyword'])){
                    $query->orWhere('b.materiel_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.type_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.materiel_no','like','%'.$data['keyword'].'%');
                }
            });
            if(isset($data['storage_id'])){
                $conentInfo ->where('a.storage_id', $data['storage_id']);
            }
            $conentInfo = $conentInfo->where('b.delete_flag', 0)
            ->whereIn('materiel_id', $materialId)
            ->groupBy('type_id')->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        $result['materiel_content_info'] = $conentInfo;
        return $result;
    }

    //采购报表
    static public function statementMaterielExport($condition, $data, $userInfo)
    {
        $materielInfo = MaterielModel::where([
            'repeal_status' => 0,
        ])
            ->from('materiel as a')
            ->where($userInfo)
            ->where(function($query) {
                $query->orWhere('pay_status', '!=', '0')
                    ->orWhere('in_storage_status', '!=', 0);
            })
            ->where($condition)
            ->get()->toArray();

        $materialId = [];//采购单id
        foreach($materielInfo as $materielValue) {
            $materialId[] = $materielValue['id'];
        }

        $amountInfo = MaterielContentModel::selectRaw(
            'SUM(num) as total_amount'
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where('b.delete_flag', 0)
            ->whereIn('materiel_id', $materialId)
            ->groupBy('a.main_id')
            ->first();

//        $amountInfo = MaterielContentModel::selectRaw('
//            SUM(num) as total_amount
//        ')
//            ->from('materiel_content as a')
//            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
//            ->where('b.repeal_status', 0)
//            ->where($condition)
//            ->where(function($query) {
//                $query->orWhere('b.pay_status', '!=', 0);
//                $query->orWhere('b.in_storage_status', '!=', 0);
//            })
//            ->groupBy('a.main_id')
//            ->first();
            $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];

//            $priceInfo = MaterielContentModel::selectRaw('
//                SUM(num * unit_price) as total_price
//            ')
//            ->from('materiel_content as a')
//            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
//            ->where('b.repeal_status', 0)
//            ->where($condition)
//            ->where(function($query) {
//                $query->orWhere('b.pay_status', '!=', 0);
//                $query->orWhere('b.in_storage_status', '!=', 0);
//            })
//            ->groupBy('a.main_id')
//            ->first();
            $priceInfo = MaterielContentModel::selectRaw('
                SUM(num * unit_price) as total_price
            ')
                ->from('materiel_content as a')
                ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                ->where('b.delete_flag', 0)
                ->whereIn('materiel_id', $materialId)
                ->groupBy('a.main_id')
                ->first();

            $result['total_price'] = empty($priceInfo)?0:$priceInfo['total_price'];

//            $result['materiel_content_info'] = MaterielContentModel::select(
//                'type_id',
//                'materiel_name',
//                'type_name',
//                'materiel_no',
//                'materiel_img',
//                DB::raw('SUM(num * unit_price) as total_unit_price'),
//                DB::raw('SUM(num) as num')
//                )
//                ->from('materiel_content as a')
//                ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
//                ->where('b.repeal_status', 0)
//                ->where($condition)
//                ->where(function($query) {
//                    $query->orWhere('b.pay_status', '!=', 0);
//                    $query->orWhere('b.in_storage_status', '!=', 0);
//                })
//                ->groupBy('type_id')->get()->toArray();

        $result['materiel_content_info'] = MaterielContentModel::select(
            'a.type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            'b.materiel_img',
            DB::raw('SUM(num * unit_price) as total_unit_price'),
            DB::raw('SUM(num) as num')
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where('b.delete_flag', 0)
            ->whereIn('materiel_id', $materialId)
            ->groupBy('type_id')->get()->toArray();

                return $result;
    }

    //采购报表详细
    static public function statementMaterielDetail($data, $condition)
    {
        $amountInfo = MaterielContentModel::selectRaw('
            SUM(num) as total_amount
        ')
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
            ->where('a.type_id', $data['type_id'])
            ->where('b.repeal_status', 0)
            ->where($condition)
            ->where(function($query) {
                $query->orWhere('b.pay_status', '!=', 0);
                $query->orWhere('b.in_storage_status', '!=', 0);
            })
            ->first();
        $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];

        $priceInfo = MaterielContentModel::select(
            DB::raw('SUM(num * unit_price) as total_price')
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
            ->where('a.type_id', $data['type_id'])
            ->where('b.repeal_status', 0)
            ->where($condition)
            ->where(function($query) {
                $query->orWhere('b.pay_status', '!=', 0);
                $query->orWhere('b.in_storage_status', '!=', 0);
            })
            ->first();
        $result['total_price'] = empty($priceInfo)?0:$priceInfo['total_price'];

        $result['materiel_content_info'] = MaterielContentModel::select(
            'type_id',
            'materiel_name',
            'type_name',
            'materiel_no',
            'materiel_img',
            'unit_price',
            'num',
            'a.purchase_time',
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
            ->where('a.type_id', $data['type_id'])
            ->where('b.repeal_status', 0)
            ->where($condition)
            ->where(function($query) {
                $query->orWhere('b.pay_status', '!=', 0);
                $query->orWhere('b.in_storage_status', '!=', 0);
            })
            ->orderBy('a.purchase_time', 'DESC')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        return $result;
    }

    //成本报表
    static public function statementCost($condition, $data)
    {
        //成本报表类型:0:商品;1:套餐;
        if(!$data['type']) {
            if(isset($data['storage_id'])){
                $condition[] = ['a.storage_id', '=', $data['storage_id']];
            }
            $result = self::getSellGoodsInfo($condition, $data);
        }
        else {
            $result = self::getSellPackageInfo($condition, $data);
        }
        return $result;
    }

    //已销售的商品统计导出数据
    static public function statisticsGoodsSoldExport($condition, $data)
    {
        //成本报表类型:0:商品;1:套餐;
        if(!$data['type']) {
            $result = self::getSellGoodsInfo($condition, $data);
        }
        else {
            $result = self::getSellPackageInfo($condition, $data);
        }
        return $result;
    }

    static private function getSellGoodsInfo($condition, $data)
    {
        //总数量
        $amountInfo = LogOutStorageModel::select(
            DB::raw('SUM(operate_num) as total_amount')
        )
            ->from('log_outstorage as a')
            ->where('a.delete_flag', 0)
            ->where('is_cancel', 0)
            ->where(function($query)use($data){
                if(!empty($data['keyword'])){
                    switch ($data['sel_type']){
                        case 1:
                            $query->where('materiel_name','like','%'.$data["keyword"].'%');
                            break;
                        case 2:
                            $query->where('type_name','like','%'.$data["keyword"].'%');
                            break;
                        case 3:
                            $query->where('materiel_no','like','%'.$data["keyword"].'%');
                            break;

                    }
                }
                if(!empty($data['storage_id'])){
                    $query->where('storage_id',$data["storage_id"]);
                }
            })
            ->whereNotIn('all_id_type',[5,7])
            ->where($condition)
            ->first();

        $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];

        //总成本
        $priceInfo = LogOutStorageModel::select(
            DB::raw('SUM(operate_num * materiel_mean_cost) as total_price')
        )
            ->from('log_outstorage as a')
            ->where('a.delete_flag', 0)
            ->where('is_cancel', 0)
            ->where(function($query)use($data){
                if(!empty($data['keyword'])){
                    switch ($data['sel_type']){
                        case 1:
                            $query->where('materiel_name','like','%'.$data["keyword"].'%');
                            break;
                        case 2:
                            $query->where('type_name','like','%'.$data["keyword"].'%');
                            break;
                        case 3:
                            $query->where('materiel_no','like','%'.$data["keyword"].'%');
                            break;
                    }
                }
                if(!empty($data['storage_id'])){
                    $query->where('storage_id',$data["storage_id"]);
                }
            })
            ->whereNotIn('all_id_type',[5,7])
            ->where($condition)
            ->first();

        $result['total_cost'] = empty($priceInfo)?0:sprintf('%.6f', $priceInfo['total_price']);

        //总售价
        $sellPriceInfo = LogOutStorageModel::select(
            DB::raw('SUM(operate_num * sell_price) as total_sell_price')
        )
            ->from('log_outstorage as a')
            ->where('is_cancel', 0)
            ->where('a.delete_flag', 0)
            ->where(function($query)use($data){
                if(!empty($data['keyword'])){
                    switch ($data['sel_type']){
                        case 1:
                            $query->where('materiel_name','like','%'.$data["keyword"].'%');
                            break;
                        case 2:
                            $query->where('type_name','like','%'.$data["keyword"].'%');
                            break;
                        case 3:
                            $query->where('materiel_no','like','%'.$data["keyword"].'%');
                            break;
                    }
                }
                if(!empty($data['storage_id'])){
                    $query->where('storage_id',$data["storage_id"]);
                }
            })
            ->whereNotIn('all_id_type',[5,7])
            ->where($condition)
            ->first();
        $result['total_sell_price'] = empty($sellPriceInfo)?0:sprintf('%.6f', $sellPriceInfo['total_sell_price']);

        //总利润
        $result['total_income'] = sprintf('%.6f',$result['total_sell_price'] -  $result['total_cost']);

        $query = LogOutStorageModel::select(
            'materiel_type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            'b.materiel_img',
            'b.delete_flag',
            'cost as total_cost',
            DB::raw('SUM(operate_num) as total_num'),

           /* DB::raw('SUM(operate_num) as total_num'),
            DB::raw('SUM(operate_num * sell_price) as total_price'),
            DB::raw('SUM(materiel_mean_cost * operate_num) as total_cost')*/
        )
            ->from('log_outstorage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.materiel_type_id')
            ->where('is_cancel', 0)
            ->where('a.delete_flag', 0)
            ->where(function($query)use($data){
                if(!empty($data['keyword'])){
                    switch ($data['sel_type']){
                        case 1:
                            $query->where('b.materiel_name','like','%'.$data["keyword"].'%');
                            break;
                        case 2:
                            $query->where('b.type_name','like','%'.$data["keyword"].'%');
                            break;
                        case 3:
                            $query->where('b.materiel_no','like','%'.$data["keyword"].'%');
                            break;

                    }
                }
                if(!empty($data['storage_id'])){
                    $query->where('a.storage_id',$data["storage_id"]);
                }
            })
            ->where($condition)
            ->whereNotIn('all_id_type',[5,7])
            ->groupBy('materiel_type_id');
            if(!empty($data['num_sort'])){
                $query->orderBy('total_num', $data['num_sort']);
            }else{
                $query->orderBy('total_cost', 'DESC');
            }

            if(!empty($data['pageSize']) || !empty($data['pageSize'])){
            $result['sell_materiel_info'] =$query->paginate($data['pageSize'],['*'], '',$data['currentPage']);
            }else{
                $result['sell_materiel_info'] =$query->get()->toArray();
            }

        return $result;
    }

    static private function getSellPackageInfo($condition, $data)
    {
        //总数量
        $amountInfo = LogPackageModel::select(
            DB::raw('SUM(num) as total_amount')
        )
            ->from('log_package as a')
            ->where('is_cancel', 0)
            ->where($condition)
            ->first();

        $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];

        //总售价
        $priceInfo = LogPackageModel::select(
            DB::raw('SUM(num * sell_price) as total_sell_price'),
        )
            ->from('sell_package_detail as a')
            ->from('log_package as a')
            ->where('is_cancel', 0)
            ->where($condition)
            ->first();

        $result['total_sell_price'] = empty($priceInfo)?0:sprintf('%.6f', $priceInfo['total_sell_price']);

        //总成本
        $totalPrice= LogPackageModel::select(
            DB::raw('SUM(num * cost) as total_price'),
        )
            ->from('sell_package_detail as a')
            ->from('log_package as a')
            ->where('is_cancel', 0)
            ->where($condition)
            ->first();

        $result['total_price'] = empty($totalPrice)?0:sprintf('%.6f', $totalPrice['total_price']);

        $result['total_income'] = sprintf('%.6f', ($result['total_sell_price'] - $result['total_price']));

        $query = LogPackageModel::select(
            'a.package_id',
            'b.package_name',
            DB::raw('SUM(num) as total_num'),
            DB::raw('SUM(sell_price * num) as total_price'),
            DB::raw('SUM(cost * num) as total_cost')
        )
            ->from('log_package as a')
            ->leftJoin('package as b', 'b.id', '=', 'a.package_id')
            ->where('is_cancel', 0)
            ->where($condition)
            ->groupBy('package_id');
            if(!empty($data['num_sort'])){
                $query->orderBy('total_num', $data['num_sort']);
            }else{
                $query->orderBy('total_cost', 'DESC');
            }
            if(!empty($data['pageSize']) || !empty($data['pageSize'])){

                $result['sell_materiel_info'] =$query->paginate($data['pageSize'],['*'], '',$data['currentPage']);
            }else{
                $result['sell_materiel_info'] =$query->get()->toArray();
            }
        return $result;
    }

    //销售报表
    static public function statementSell($condition, $data)
    {
        $sellIdArr = [];
        if(!empty($data['storage_id'])){

            $sellIdArr = LogOutStorageModel::where([
                'all_id_type' => 2,
                'storage_id' => $data['storage_id'],
                'main_id' => $condition['main_id']
            ])->distinct()->pluck('all_id');
        }
        $query = SellModel::select(
            'id',
            'final_money',
            'sell_date',
            'order_no',
            'customer_name',
            'real_money',
            'other_charges'
        )->where([
            'repeal_status' => 0,
            'delete_flag' => 0,
            ['out_status','!=',0]
        ])->where($condition);
        if(!empty($data['storage_id'])){
            $query->whereIn('id',$sellIdArr);
        }
        $sellList = $query->orderBy('sell_date', 'DESC')
        ->get()->toArray();
        $totalSellMoney = 0;
        $totalSellCost = 0;
        $totalSellDebt = 0;
        $totalSellIncome = 0;
        if(!empty($sellList)){
            foreach ($sellList as &$value){
                $selParam = [
                    DB::raw('SUM(operate_num) as total_num'),
                    DB::raw('SUM(operate_num * materiel_mean_cost) as total_cost'),
                    DB::raw('SUM(operate_num * sell_price)-SUM(operate_num * materiel_mean_cost) as total_income')
                ];
                $outCondtion = [
                    'all_id_type' => 2,
                    'all_id' => $value['id']
                ];
                if(!empty($data['storage_id'])){
                    $outCondtion['storage_id'] = $data['storage_id'];
                }
                $outInfo = LogOutStorageModel::select($selParam)
                ->where($outCondtion)->first();
                $value['total_num'] = sprintf('%.6f', $outInfo['total_num'])?? 0;
                $value['total_income'] = sprintf('%.6f', $outInfo['total_income']) ?? 0;
                $value['total_debt'] = sprintf('%.6f',($value['final_money'] + $value['other_charges']) - $value['real_money']);
                $totalSellMoney += sprintf('%.6f',$value['final_money']);
                $totalSellCost += $outInfo['total_cost'] ?? 0;
                $totalSellDebt += $value['total_debt'];
                $totalSellIncome += $value['total_income'];
            }
            if(!empty($data['num_sort'])){//数量排序
                $paramSort = array_column($sellList,'total_num');
                $sort = $data['num_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$sellList);
            }
            if(!empty($data['income_sort'])){//利润排序
                $paramSort = array_column($sellList,'total_income');
                $sort = $data['income_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$sellList);
            }
            if(!empty($data['debt_sort'])){//利润排序
                $paramSort = array_column($sellList,'total_debt');
                $sort = $data['debt_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$sellList);
            }
            if(!empty($data['percentage_sort'])){//百分比排序
                $paramSort = array_column($sellList,'final_money');
                $sort = $data['percentage_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$sellList);
            }
        }
        if(!isset($data['currentPage'])){
            return $exportData = [
                'total_sell_money' => $totalSellMoney,
                'total_sell_cost' => $totalSellCost,
                'total_sell_debt' => $totalSellDebt,
                'total_sell_income' => $totalSellIncome,
                'list' => $sellList,
            ];
        }
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($sellList), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        return [
            'total_sell_money'=>$totalSellMoney,
            'total_sell_cost'=>$totalSellCost,
            'total_sell_debt'=>$totalSellDebt,
            'total_sell_income'=>$totalSellIncome,
            'total' => count($sellList),
            'current_page' => $currentPage,
            'next_page_url' => count($result) < $data['pageSize']?null:config('app.url')."statement_sell?=".($data['currentPage']+1),
            'prev_page_url' => $currentPage==1?null:config('app.url')."statement_sell?=".($currentPage-1),
            "path" => config('app.url')."statement_sell",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
    }
    //销售报表-导出
    static public function statementSellExport($condition, $data)
    {
        $moneyInfo = SellModel::select(
        DB::raw('SUM(final_money) as total_money')
        )->where([
            'repeal_status' => 0,
            'out_status' => 2,
            'pay_status' => 2,
            'delete_flag' => 0
        ])
        ->where($condition)
        ->where(function($query) {
            $query->orWhere('out_status', '!=', 0);
            $query->orWhere('pay_status', '!=', 0);
        })->first();
        $result['total_money'] = empty($moneyInfo)?0:$moneyInfo['total_money'];
        $result['sell_info'] = SellModel::select(
        'customer_name',
        'order_no',
        'id',
        'final_money',
        'sell_date'
        )->where([
            'repeal_status' => 0,
            'out_status' => 2,
            'pay_status' => 2,
            'delete_flag' => 0
        ])->where($condition)
        ->where(function($query) {
            $query->orWhere('out_status', '!=', 0);
            $query->orWhere('pay_status', '!=', 0);
        })
        ->orderBy('sell_date', 'DESC')
        ->get()->toArray();
        $result['total_cost_price'] = 0;
        if(!empty($result['sell_info'])){
            foreach ($result['sell_info'] as &$val){
                $goodsInfo = SellGoodsDetail::select(
                    DB::raw('SUM(out_num) as goods_num'),
                    DB::raw('SUM(cost_price) as cost_price')
                    )->where([
                    'sell_id'=>$val['id'],
                    'repeal_status'=>0
                ])->first();
                $val['goods_num'] = $goodsInfo['goods_num']??0;
                $val['cost_price'] = $goodsInfo['cost_price']??0;
                $val['profit'] = $val['final_money'] - $goodsInfo['cost_price'];
                $result['total_cost_price'] += $val['cost_price'];
            }
        }
        $result['total_profit'] = $result['total_money']-$result['total_cost_price'];
        return $result;
    }
    //仓库报表
    static public function statementStorage($condition, $storageIdArr = [])
    {
        $result['storage_info'] = StorageModel::select(
            'a.id',
            'storage_name',
            'storage_address',
            'username'
        )
            ->from('storage as a')
            ->leftJoin('admin as b','b.id','=','a.user_id')
            ->where(function($query)use($storageIdArr,$condition){
                if(!empty($storageIdArr)){
                    $query->whereIn('a.id',$storageIdArr);
                }else{
                    $query->where($condition);
                }
            })
            ->where('a.delete_flag', 0)
            ->get()->toArray();

        $storageManageInfo = StorageManageModel::select(
            'storage_id',
            DB::raw('SUM(in_storage_num) as total_amount'),
            DB::raw('SUM(in_storage_num * materiel_mean_cost) as total_cost')
        )
            ->from('storage_manage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where('a.delete_flag', 0)
            ->where('b.delete_flag', 0)
            ->where(function($query)use($storageIdArr,$condition){
                if(!empty($storageIdArr)){
                    $query->whereIn('storage_id',$storageIdArr);
                }else{
                    $query->where($condition);
                }
            })
            ->orderBy('total_amount', 'desc')
            ->groupBy('storage_id')
            ->get()->toArray();

        foreach($result['storage_info'] as $key => &$value) {
            foreach($storageManageInfo as $val) {
                if($value['id'] == $val['storage_id']) {
                    $value['storage_detail_info'] = [
                        'total_amount' => $val['total_amount'],
                        'total_cost' => $val['total_cost']
                    ];
                }
            }
        }
        return $result;
    }

    //仓库报表
    static public function statementStorageExport($condition)
    {
        $result['storage_info'] = StorageModel::select(
            'a.id',
            'storage_name',
            'storage_address',
            'username'
            )
            ->from('storage as a')
            ->leftJoin('admin as b','b.id','=','a.user_id')
            ->where($condition)
            ->where('a.delete_flag', 0)
            ->get()->toArray();

            $storageManageInfo = StorageManageModel::select(
                'storage_id',
                DB::raw('SUM(in_storage_num) as total_amount'),
                DB::raw('SUM(in_storage_num * materiel_mean_cost) as total_cost')
                )
                ->from('storage_manage as a')
                ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
                ->where('a.delete_flag', 0)
                ->where('b.delete_flag', 0)
                ->where($condition)
                ->groupBy('storage_id')
                ->get()->toArray();

                foreach($result['storage_info'] as $key => &$value) {
                    foreach($storageManageInfo as $val) {
                        if($value['id'] == $val['storage_id']) {
                            $value['storage_detail_info'] = [
                                'total_amount' => $val['total_amount'],
                                'total_cost' => $val['total_cost']
                            ];
                        }
                    }
                }
                return $result;
    }

    //仓库报表详细
    static public function statementStorageDetail($storageId, $data)
    {
        $condition = [];
        if(!empty($storageId)) {
            $condition['storage_id'] = ['' => ['EQ' => $storageId]];
        }
        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }
        $condition1 = [];
        if(!empty($startTime) && !empty($endTime)) {
            $condition1[] = ['in_storage_time', '>=', $startTime];
            $condition1[] = ['in_storage_time', '<=', $endTime];
        }else if(!empty($startTime) && empty($endTime)) {
            $condition1[] = ['in_storage_time', '>=', $startTime];
        }else if(empty($startTime) && !empty($endTime)) {
            $condition1[] = ['in_storage_time', '<=', $endTime];
        }
        $data['num_sort'] = isset($data['num_sort'])?$data['num_sort']:'desc';
        $result['detail_info'] = StorageManageModel::select(
            'type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            DB::raw('SUM(in_storage_num) as total_amount'),
            DB::raw('SUM(in_storage_num * materiel_mean_cost) as total_cost')
        )
            ->from('storage_manage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->leftJoin('materiel_class as c', 'c.id', '=', 'a.materiel_class_id')
            ->leftJoin('materiel_class as d', 'd.id', '=', 'c.parent_id')
            ->where('a.main_id', $data['main_id'])
            ->where([
                'a.delete_flag'=>0,
                'b.delete_flag'=>0,
                'c.delete_flag'=>0,
                'd.delete_flag'=>0,
            ])->where(function($query) use($data){
                if(!empty($data['keyword'])){
                    $query->orWhere('b.materiel_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.type_name','like','%'.$data['keyword'].'%');
                    $query->orWhere('b.materiel_no','like','%'.$data['keyword'].'%');
                }
            })
            ->where($condition)
            ->where($condition1)
            ->orderBy('total_amount',  $data['num_sort'])
            ->groupBy('type_id')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        return $result;
    }

    //仓库报表详细-导出
    static public function inventoryStatisticsExport($storageId, $data)
    {
        $condition = [];
        if(!empty($storageId)) {
            $condition['storage_id'] = ['' => ['EQ' => $storageId]];
        }

        $result['detail_info'] = StorageManageModel::select(
            'type_id',
            'b.materiel_name',
            'b.type_name',
            'b.materiel_no',
            DB::raw('SUM(in_storage_num) as total_amount'),
            DB::raw('SUM(in_storage_num * materiel_mean_cost) as total_cost')
            )
            ->from('storage_manage as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.type_id')
            ->where('b.delete_flag', 0)
            ->where('a.main_id', $data['a.main_id'])
            ->where($condition)
            ->groupBy('type_id')
            ->get()->toArray();

            return $result;
    }

    static public function statementCustomer($data, $condition)
    {
        $thisYearTimestamp = Carbon::now()->startOfYear()->timestamp; // 获取当前年份的第一天时间戳
        //采购信息
        $materielInfo = MaterielModel::select(
            'id',
            'supplier_customer_id as customer_id',
            'supplier_name as customer_name'
        )
            ->where([
                'repeal_status' => 0,
                'delete_flag' => 0,
                ['created_at','>=',$thisYearTimestamp]
            ]);
        if(!empty($data['keyword'])) {
            $materielInfo->where('supplier_name', 'LIKE', '%'.$data['keyword'].'%');
        }
        $materielInfo = $materielInfo->where($condition)->get();
        if(!empty($materielInfo)) $materielInfo = $materielInfo->toArray();
        //销售信息
        $sellInfo = SellModel::select(
            'id',
            'customer_id',
            'customer_name'
        )
            ->where([
                'repeal_status' => 0,
                'delete_flag' => 0,
                ['created_at','>=',$thisYearTimestamp]
                ]);
            if(!empty($data['keyword'])) {
                $sellInfo->where('customer_name', 'LIKE', '%'.$data['keyword'].'%');
            }
            $sellInfo = $sellInfo->where($condition)->get();
        if(!empty($sellInfo)) $sellInfo = $sellInfo->toArray();
        //销售信息
        $salesInfo = SalesReturnModel::select(
            'id',
            'customer_id',
            'customer_name'
        )
            ->where([
                'repeal_status' => 0,
                'delete_flag' => 0,
                ['created_at','>=',$thisYearTimestamp]
            ]);
            if(!empty($data['keyword'])) {
                $salesInfo->where('customer_name', 'LIKE', '%'.$data['keyword'].'%');
            }
        $salesInfo = $salesInfo->where($condition)->get();
        if(!empty($salesInfo)) $salesInfo = $salesInfo->toArray();
        $materielId = [];
        $materielSupplierInfo = [];
        foreach($materielInfo as $value) {
            $materielId[] = $value['id'];
            $materielSupplierInfo[] = [
                'customer_name' => $value['customer_name'],
                'customer_id' => $value['customer_id']
            ];
        }

        $sellId = [];
        $sellCustomerInfo = [];
        foreach($sellInfo as $val) {
            $sellId[] = $val['id'];
            $sellCustomerInfo[] = [
                'customer_name' => $val['customer_name'],
                'customer_id' => $val['customer_id']
            ];
        }

        $salesReturnId = [];
        $salesCustomerInfo = [];
        foreach($salesInfo as $v) {
            $salesReturnId[] = $v['id'];
            $salesCustomerInfo[] = [
                'customer_name' => $v['customer_name'],
                'customer_id' => $v['customer_id']
            ];
        }

        $datas = array_merge_recursive(
            $materielSupplierInfo,
            $sellCustomerInfo,
            $salesCustomerInfo
        );

        $arr = [];
        foreach($datas as $kkkk => $vals) {
            if(in_array($vals['customer_id'], $arr)) {
                unset($datas[$kkkk]);
            }
            else {
                $arr[] = $vals['customer_id'];
            }
        }

        //总应付金额-采购
        $materielShouldPayInfo = self::materielShouldPayInfo($materielId);
        //销售-总应付金额
        $sellShouldPayInfo = self::sellShouldPayInfo($sellId);
        //实付金额-销售
        $sellFinalPayInfo = self::sellFinalPayMoney($sellId);
        //采购商品数量
        $materielGoodsInfo = self::customerMaterielGoodsList($materielId);
        //销售商品数量
        $sellGoodsInfo = self::customerSellGoodsList($sellId);
        //退货-应付金额
        $salesReturnPayInfo =  self::salesReturnPayMoney($salesReturnId);

        $result = [];
        foreach($datas as $k1 => $v1) {
            $result[$k1]['customer_id'] = $v1['customer_id'];
            $result[$k1]['customer_name'] = $v1['customer_name'];
            $result[$k1]['materiel_money'] = 0;
            $result[$k1]['sell_money'] = 0;
            $result[$k1]['income_money'] = 0;
            $result[$k1]['customer_debt'] = 0;
            $result[$k1]['sales_return_money'] = 0;
        }

        $debtInfo = [];
        foreach($sellShouldPayInfo as $key => $vvv1) {
            foreach($sellFinalPayInfo as $vvv2) {
                if($vvv1['customer_id'] == $vvv2['customer_id']) {
                    $debtInfo[$key] = [
                        'customer_name' => $vvv2['customer_name'],
                        'customer_debt' => $vvv1['sell_money'] - $vvv2['final_pay_money']
                    ];
                }
            }
        }

        foreach($result as &$vv1) {
            if(!empty($materielShouldPayInfo)) {
                foreach($materielShouldPayInfo as $vv2) {
                    if($vv2['customer_id'] == $vv1['customer_id']) {
                        $vv1['materiel_money'] = $vv2['materiel_money'];
                    }
                }
            }

            if(!empty($sellShouldPayInfo)) {
                foreach($sellShouldPayInfo as $vv3) {
                    if($vv3['customer_id'] == $vv1['customer_id']) {
                        $vv1['sell_money'] = $vv3['sell_money'];
                    }
                }
            }

            if(!empty($debtInfo)) {
                foreach($debtInfo as $vv4) {
                    if($vv4['customer_name'] == $vv1['customer_name']) {
                        $vv1['customer_debt'] = sprintf('%.6f', $vv4['customer_debt']);
                    }
                }
            }

            if(!empty($salesReturnPayInfo)) {
                foreach($salesReturnPayInfo as $vv5) {
                    if($vv5['customer_id'] == $vv1['customer_id']) {
                        $vv1['sales_return_money'] = $vv5['sales_return_money'];
                    }
                }
            }

            if(!empty($sellGoodsInfo)) {
                foreach($sellGoodsInfo as $vv6) {
                    if($vv6['customer_id'] == $vv1['customer_id']) {
                        $vv1['total_num'] = $vv6['total_num'];
                    }else{
                        $vv1['total_num'] = 0;
                    }
                }
            }

            if(!empty($materielGoodsInfo)) {
                foreach($materielGoodsInfo as $vv7) {
                    if($vv7['customer_id'] == $vv1['customer_id']) {
                        $vv1['materiel_total_num'] = $vv7['total_num'];
                    }else{
                        $vv1['materiel_total_num'] = 0;
                    }
                }
            }
        }
        $result = array_values($result);
        foreach($result as &$v11) {
            $v11['income_money'] = $v11['sell_money'] - ($v11['materiel_money'] + $v11['sales_return_money']);
            unset($v11['sales_return_money']);
        }
        if(!empty($result)){
            foreach ($result as &$v){
                $info=SupplierCustomerModel::where('id',$v['customer_id'])
                    ->where(function($query) use($data){
                        if(!empty($data['keyword'])){
                            $query->orWhere('compony_name','like','%'.$data['keyword'].'%');
                        }
                    })
                    ->where('delete_flag',0)->first();
                $v['compony_name'] = $info['compony_name']??'';
                if(!empty($info)) $tjList[] = $v;
            }
            $result = $tjList;
            if(!empty($data['customer_debt_sort'])){//欠款排序
                $customerDebtSort = array_column($result,'customer_debt');
                $sort = $data['customer_debt_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }

            if(!empty($data['income_money_sort'])){//利润排序
                $customerDebtSort = array_column($result,'income_money');
                $sort = $data['income_money_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }

            if(!empty($data['sell_money_sort'])){//销售额排序
                $customerDebtSort = array_column($result,'sell_money');
                $sort = $data['sell_money_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }

            if(!empty($data['total_num_sort'])){//数量排序
                $customerDebtSort = array_column($result,'total_num');
                $sort = $data['total_num_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }

            if(!empty($data['purchase_money_sort'])){//采购金额排序
                $customerDebtSort = array_column($result,'materiel_money');
                $sort = $data['purchase_money_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }
        }
        if(!isset($data['pageSize'])){
            return $result;
        }
        $returnResult = array_slice($result, --$data['currentPage'] * $data['pageSize'], $data['pageSize']);

        if(count($result) < $data['pageSize']) {
            $finalResult['next_page_url'] = null;
        }
        else {
            $finalResult['next_page_url'] = empty($returnResult)?null:'asdfa';
        }
        $finalResult['total'] = count($result);
        $finalResult['customer_report'] = $returnResult;

        return $finalResult;
    }

    static public function statementCustomerExport($data, $condition)
    {
        //采购信息
        $materielInfo = MaterielModel::select(
            'id',
            'supplier_customer_id as customer_id',
            'supplier_name as customer_name'
            )
            ->where([
                'repeal_status' => 0,
            ]);
            if(!empty($data['keyword'])) {
                $materielInfo->where('supplier_name', 'LIKE', '%'.$data['keyword'].'%');
            }
            $materielInfo = $materielInfo->where(function($query) {
                /* $query->orWhere('pay_status', '!=', 0);
                 $query->orWhere('in_storage_status', '!=', 0); */
            })

            ->where($condition)
            ->get()->toArray();

            //销售信息
            $sellInfo = SellModel::select(
                'id',
                'customer_id',
                'customer_name'
                )
                ->where('repeal_status', 0);
                if(!empty($data['keyword'])) {
                    $sellInfo->where('customer_name', 'LIKE', '%'.$data['keyword'].'%');
                }
                $sellInfo = $sellInfo->where(function($query) {
                    /*  $query->orWhere('out_status', '!=', 0);
                     $query->orWhere('pay_status', '!=', 0); */
                })
                ->where($condition)
                ->get()->toArray();

                //销售信息
                $salesInfo = SalesReturnModel::select(
                    'id',
                    'customer_id',
                    'customer_name'
                    )
                    ->where('repeal_status', 0);
                    if(!empty($data['keyword'])) {
                        $salesInfo->where('customer_name', 'LIKE', '%'.$data['keyword'].'%');
                    }
                    $salesInfo = $salesInfo->where(function($query) {
                        /* $query->orWhere('out_status', '!=', 0);
                         $query->orWhere('pay_status', '!=', 0); */
                    })

                    ->where($condition)
                    ->get()->toArray();

                    $materielId = [];
                    $materielSupplierInfo = [];
                    foreach($materielInfo as $value) {
                        $materielId[] = $value['id'];
                        $materielSupplierInfo[] = [
                            'customer_name' => $value['customer_name'],
                            'customer_id' => $value['customer_id']
                        ];
                    }

                    $sellId = [];
                    $sellCustomerInfo = [];
                    foreach($sellInfo as $val) {
                        $sellId[] = $val['id'];
                        $sellCustomerInfo[] = [
                            'customer_name' => $val['customer_name'],
                            'customer_id' => $val['customer_id']
                        ];
                    }

                    $salesReturnId = [];
                    $salesCustomerInfo = [];
                    foreach($salesInfo as $v) {
                        $salesReturnId[] = $v['id'];
                        $salesCustomerInfo[] = [
                            'customer_name' => $v['customer_name'],
                            'customer_id' => $v['customer_id']
                        ];
                    }

                    $datas = array_merge_recursive(
                        $materielSupplierInfo,
                        $sellCustomerInfo,
                        $salesCustomerInfo
                        );

                    $arr = [];
                    foreach($datas as $kkkk => $vals) {
                        if(in_array($vals['customer_id'], $arr)) {
                            unset($datas[$kkkk]);
                        }
                        else {
                            $arr[] = $vals['customer_id'];
                        }
                    }

                    //总应付金额-采购
                    $materielShouldPayInfo = self::materielShouldPayInfo($materielId);
                    //销售-总应付金额
                    $sellShouldPayInfo = self::sellShouldPayInfo($sellId);
                    //实付金额-销售
                    $sellFinalPayInfo = self::sellFinalPayMoney($sellId);

                    //退货-应付金额
                    $salesReturnPayInfo =  self::salesReturnPayMoney($salesReturnId);

                    $result = [];
                    foreach($datas as $k1 => $v1) {
                        $result[$k1]['customer_id'] = $v1['customer_id'];
                        $result[$k1]['customer_name'] = $v1['customer_name'];
                        $result[$k1]['materiel_money'] = 0;
                        $result[$k1]['sell_money'] = 0;
                        $result[$k1]['income_money'] = 0;
                        $result[$k1]['customer_debt'] = 0;
                        $result[$k1]['sales_return_money'] = 0;
                    }

                    $debtInfo = [];
                    foreach($sellShouldPayInfo as $key => $vvv1) {
                        foreach($sellFinalPayInfo as $vvv2) {
                            if($vvv1['customer_id'] == $vvv2['customer_id']) {
                                $debtInfo[$key] = [
                                    'customer_name' => $vvv2['customer_name'],
                                    'customer_debt' => $vvv1['sell_money'] - $vvv2['final_pay_money']
                                ];
                            }
                        }
                    }

                    foreach($result as &$vv1) {
                        if(!empty($materielShouldPayInfo)) {
                            foreach($materielShouldPayInfo as $vv2) {
                                if($vv2['customer_id'] == $vv1['customer_id']) {
                                    $vv1['materiel_money'] = $vv2['materiel_money'];
                                }
                            }
                        }

                        if(!empty($sellShouldPayInfo)) {
                            foreach($sellShouldPayInfo as $vv3) {
                                if($vv3['customer_id'] == $vv1['customer_id']) {
                                    $vv1['sell_money'] = $vv3['sell_money'];
                                }
                            }
                        }

                        if(!empty($debtInfo)) {
                            foreach($debtInfo as $vv4) {
                                if($vv4['customer_name'] == $vv1['customer_name']) {
                                    $vv1['customer_debt'] = sprintf('%.6f', $vv4['customer_debt']);
                                }
                            }
                        }

                        if(!empty($salesReturnPayInfo)) {
                            foreach($salesReturnPayInfo as $vv5) {
                                if($vv5['customer_id'] == $vv1['customer_id']) {
                                    $vv1['sales_return_money'] = $vv5['sales_return_money'];
                                }
                            }
                        }
                    }

                    $result = array_values($result);
                    foreach($result as &$v11) {

                        $v11['income_money'] = $v11['sell_money'] - ($v11['materiel_money'] + $v11['sales_return_money']);
                        unset($v11['sales_return_money']);
                    }

                    if(!empty($result)){
                        $tjList = [];
                        foreach ($result as &$v){
                            $info = SupplierCustomerModel::where([
                                'id' => $v['customer_id'],
                                'main_id' => $condition['main_id'],
                                'delete_flag' => 0
                            ])->first();
                            $v['compony_name'] = $info['compony_name']??'';
                            if(!empty($info)) $tjList[] = $v;
                        }
                        $result = $tjList;
                    }
                    return $result;

    }

    private static function salesReturnPayMoney($salesReturnId)
    {
        return SalesReturnModel::select(
            'customer_id',
            'customer_name',
            DB::raw('SUM(final_money) as sales_return_money')
        )
            ->where('repeal_status', 0)
            ->whereIn('id', $salesReturnId)
            ->where(function($query) {
              /*   $query->orWhere('out_status', '!=', 0);
                $query->orWhere('pay_status', '!=', 0); */
            })
            ->groupBy('customer_id')
            ->groupBy('customer_name')
            ->get()->toArray();
    }

    //销售单应付金额
    static private function sellShouldPayInfo($sellId)
    {
        return SellModel::select(
            'customer_id',
            'customer_name',
            DB::raw('SUM(final_money) as sell_money')
        )
            ->where('repeal_status', 0)
            ->whereIn('id', $sellId)
          /*   ->where(function($query) {
                $query->orWhere('out_status', '!=', 0);
                $query->orWhere('pay_status', '!=', 0);
            }) */
            ->groupBy('customer_id')
            ->groupBy('customer_name')
            ->get()->toArray();
    }

    //实付金额-销售
    static private function sellFinalPayMoney($sellId)
    {
        return SellModel::select(
            'customer_id',
            'customer_name',
            DB::raw('SUM(expend) as final_pay_money')
        )
            ->from('sell as a')
            ->leftJoin('sell_pay_record as b', 'a.id', '=', 'b.sell_id')
            ->where('repeal_status', 0)
            ->whereIn('a.id', $sellId)
          /*   ->where(function($query) {
                $query->orWhere('out_status', '!=', 0);
                $query->orWhere('pay_status', '!=', 0);
            }) */
            ->groupBy('customer_id')
            ->groupBy('customer_name')
            ->get()->toArray();
    }

    //采购单应付金额
    static private function materielShouldPayInfo($materielId)
    {
        return MaterielModel::select(
            'supplier_customer_id as customer_id',
            'supplier_name',
            DB::raw('SUM(final_money) as materiel_money')
        )
            ->where('repeal_status', 0)
            ->whereIn('id', $materielId)
            ->where(function($query) {
              /*   $query->orWhere('pay_status', '!=', 0);
                $query->orWhere('in_storage_status', '!=', 0); */
            })
            ->groupBy('supplier_customer_id')
            ->groupBy('supplier_name')
            ->get()->toArray();
    }

    //客户订单详细
    static public function statementCustomerDetail($data, $condition)
    {
        $startTimeArr = [];
        $startTime = [];
        $endTimeArr = [];
        $endTime = [];

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }
        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }
        $cond = [];
        if(!empty($startTime) && !empty($endTime)) {
            $cond[] = ['created_at', '>=', $startTime];
            $cond[] = ['created_at', '<=', $endTime];
        }elseif(!empty($startTime) && empty($endTime)) {
            $cond[] = ['created_at', '>=', $startTime];
        }elseif(empty($startTime) && !empty($endTime)) {
            $cond[] = ['created_at', '<=', $endTime];
        }
        if(!empty($data['is_share_purchase'])){
            $condition = [];
            $condition['main_id'] = $data['main_id'];
        }else{
            if($data['main_id'] == $data['user_id']) {
                $condition['main_id'] = ['EQ' => $data['main_id']];
            } else {
                $condition['user_id'] = ['EQ' => $data['user_id']];
            }
        }
        //获取所有相关采购单id
        $getCustomerMaterielId= self::getCustomerMaterielId($data, $condition, $cond);
        $materielId = [];
        foreach($getCustomerMaterielId as $value) {
            $materielId[] = $value['id'];
        }
        if(empty($materielId)) {
            $arr['materiel_total_num'] = 0;
            $arr['materiel_total_money'] = 0;
        } else {
            //获取采购单总金额-总实付金额
            $getCustomerMaterielFinalMoney = self::getCustomerMaterielFinalMoney($materielId);
            //获取采购单内容信息-数量
            $getCustomerMaterielContentInfo = self::getCustomerMaterielContentInfo($materielId);
            $arr['materiel_total_num'] = $getCustomerMaterielContentInfo['total_materiel_num'];
            $arr['materiel_total_money'] = $getCustomerMaterielFinalMoney['total_final_money'];
        }

        if(!empty($data['is_share_sell'])){
            $condition = [];
            $condition['main_id'] = $data['main_id'];
        }else{
            if($data['main_id'] == $data['user_id']) {
                $condition['main_id'] = ['EQ' => $data['main_id']];
            } else {
                $condition['user_id'] = ['EQ' => $data['user_id']];
            }
        }

        //获取所有销售单id信息
        $getCustomerSellId = self::getCustomerSellId($data, $condition, $cond);
        $sellId = [];
        foreach($getCustomerSellId as $val) {
            $sellId[] = $val['id'];
        }

        if(empty($sellId)) {
            $arr['sell_total_num'] = 0;
            $arr['sell_final_money'] = 0;
            $arr['sell_actual_pay'] = 0;
            $arr['sell_debt'] = 0;
            $arr['total_income'] = 0;
        } else {
            //销售单总销售金额
            $getCustomerSellMoney = self::getCustomerSellMoney($sellId);
            //销售单商品总件数
            $getCustomerSellMaterielAmountInfo = self::getCustomerSellMaterielAmountInfo($sellId);
            //销售单套餐总件数
            $getCustomerSellPackageAmountInfo = self::getCustomerSellPackageAmountInfo($sellId);
            //销售单实付金额
            $getCustomerSellFinalMoney = self::getCustomerSellFinalMoney($sellId);
            if(!empty($data['is_share_sell'])){
                $condition = [];
                $condition['main_id'] = $data['main_id'];
            }else{
                if($data['main_id'] == $data['user_id']) {
                    $condition['main_id'] = ['EQ' => $data['main_id']];
                } else {
                    $condition['user_id'] = ['EQ' => $data['user_id']];
                }
            }
            //退货信息-总金额
            $getCustomerSalesReturnInfo = self::getCustomerSalesReturnInfo($data, $condition, $cond);
            $salesReturnTotalMoney = empty($getCustomerSalesReturnInfo['sales_return_money'])?0:$getCustomerSalesReturnInfo['sales_return_money'];
            $sellMaterielNum = empty($getCustomerSellMaterielAmountInfo)?0:$getCustomerSellMaterielAmountInfo['sell_materiel_total_num'];
            $sellPackageNum = empty($getCustomerSellPackageAmountInfo)?0:$getCustomerSellPackageAmountInfo['sell_package_total_num'];
            $arr['sell_total_num'] = $sellMaterielNum + $sellPackageNum;//总商品数量
            $arr['sell_final_money'] = $getCustomerSellMoney['total_final_money'];//订单总额
            //订单实付
            $arr['sell_actual_pay'] = empty($getCustomerSellFinalMoney['sell_final_pay_money'])?0:$getCustomerSellFinalMoney['sell_final_pay_money'];
            //总欠款
            $arr['sell_debt'] = sprintf('%.6f', $arr['sell_final_money'] - $arr['sell_actual_pay']);

            $totalIncode = $arr['sell_final_money'] - $arr['materiel_total_money'] - $salesReturnTotalMoney;
            $arr['total_income'] = sprintf('%.6f', $totalIncode);//总利润
        }
        $param = 'materiel_num';
        //统计类型;0:采购;1:销售;
        if($data['type'] == 0) {
            if(!empty($data['is_share_purchase'])){
                $condition = [];
                $condition['main_id'] = $data['main_id'];
            }else{
                if($data['main_id'] == $data['user_id']) {
                    $condition['main_id'] = ['EQ' => $data['main_id']];
                } else {
                    $condition['user_id'] = ['EQ' => $data['user_id']];
                }
            }
            $result = self::getMaterielList($data, $condition, $materielId, $cond, 1);
        } else {
            $param = 'sell_num';
            if(!empty($data['is_share_sell'])){
                $condition['main_id'] = $data['main_id'];
            }else{
                if($data['main_id'] == $data['user_id']) {
                    $condition['main_id'] = ['EQ' => $data['main_id']];
                } else {
                    $condition['user_id'] = ['EQ' => $data['user_id']];
                }
            }
            $result = self::getSellList($data, $condition, $sellId, $cond,1);
        }
        $array = [];
        if(!empty($result)){
            if(!empty($data['debt_sort'])){//欠款排序
                $customerDebtSort = array_column($result,'debt');
                $sort = $data['debt_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }
            if(!empty($data['money_sort'])){//金额排序
                $customerDebtSort = array_column($result,'final_money');
                $sort = $data['money_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }
            if(!empty($data['num_sort'])){//数量排序
                //统计类型;0:采购;1:销售;
                $customerDebtSort = array_column($result,$param);
                $sort = $data['num_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($customerDebtSort,$sort,$result);
            }
            $array = $result;
        }
        if(empty($data['currentPage'])){
            $arr['list_info'] = $result;
            return $arr;
        }
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($array), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        $result = [
            'total' => count($array),
            'current_page' => $currentPage,
            'next_page_url' => count($result) < $data['pageSize']?null:config('app.url')."statement_customer_detail?=".($data['currentPage']+1),
            'prev_page_url' => $currentPage==1?null:config('app.url')."statement_customer_detail?=".($currentPage-1),
            "path" => config('app.url')."statement_customer_detail",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
        $arr['list_info'] = $result;
        return $arr;
    }

    static private function getSellList($data, $condition, $sellId, $cond =[])
    {
        $info = SellModel::select(
            'id',
            'order_no',
            'sell_date',
            'final_money'
        )->where($condition)
        ->where('repeal_status', 0)
        ->where($cond)
        ->where(function($query) use($data){
            if(!empty($data['keyword'])){
                $query->where('order_no',$data['keyword']);
            }
        })
        ->whereIn('id', $sellId)
        ->orderBy('id', 'DESC')
        ->get()->toArray();

        foreach($info as &$value) {
            $sellPayInfo = self::getSingleSellPayInfo($value['id']);

            $value['sell_num'] = self::getSingleSellTotalNum($value['id']);
            $value['debt'] = sprintf('%.6f', $value['final_money'] - $sellPayInfo['total_money']);//欠款
        }
        return $info;
    }

    static private function getSingleSellTotalNum($sellId) {
        $sellInfo = SellGoodsDetailModel::select(
            DB::raw('SUM(num) as sell_matereil_num')
        )
            ->where('sell_id', $sellId)
            ->first();

        $sellPackageInfo = SellPackageDetailModel::select(
            DB::raw('SUM(num) as sell_package_num')
        )
            ->where('sell_id', $sellId)
            ->first();

        $sellMaterielNum = empty($sellInfo['sell_matereil_num'])?0:$sellInfo['sell_matereil_num'];
        $sellPackageNum = empty($sellPackageInfo['sell_package_num'])?0:$sellPackageInfo['sell_package_num'];

        return $sellMaterielNum + $sellPackageNum;
    }

    static private function getSingleSellPayInfo($sellId)
    {
        return SellPayRecordModel::select(
            DB::raw('SUM(expend) as total_money')
        )
            ->where('sell_id', $sellId)->first();
    }

    //获取供应商或客户采购信息
    static private function getMaterielList($data, $condition, $materielId, $cond =[], $flag =0)
    {
        $info =  MaterielModel::select(
            'id',
            'purchase_no',
            'purchase_time',
            'final_money'
        )->where($condition)
        ->where('repeal_status', 0)
        ->where($cond)
        ->where(function($query) use($data){
            if(!empty($data['keyword'])){
                $query->where('purchase_no',$data['keyword']);
            }
        })->whereIn('id', $materielId)
        ->orderBy('id', 'DESC')
        ->get()->toArray();

        foreach($info as &$value) {
            $materielPayInfo = self::getSingleMaterielPayInfo($value['id']);
            //采购单采购总数
            $value['materiel_num'] = self::getSingleMatereilNum($value['id']);
            $value['debt'] = sprintf('%.6f', $value['final_money'] - $materielPayInfo['total_money']);//欠款
        }
        return $info;
    }

    //获取采购单采购总数
    static private function getSingleMatereilNum($id)
    {
        $info = MaterielContentModel::select(
            DB::raw('SUM(num) as total_num')
        )
            ->where('materiel_id', $id)->first();

        return empty($info['total_num'])?0:$info['total_num'];
    }

    static private function getSingleMaterielPayInfo($materielId)
    {
        return MaterielPayHistoryModel::select(
            DB::raw('SUM(money) as total_money')
        )
            ->where('materiel_id', $materielId)->first();
    }

    //退货信息-总金额
    static private function getCustomerSalesReturnInfo($data, $condition, $cond = [])
    {
        return SalesReturnModel::select(
            DB::raw('SUM(final_money) as sales_return_money')
        )
            ->where($condition)
            ->where($cond)
            ->where(function($query) use($data){
                if(!empty($data['keyword'])){
                    $query->where('order_no',$data['keyword']);
                }
            })
            ->where('customer_id', $data['customer_id'])
            ->where('customer_name', $data['customer_name'])
            ->where('repeal_status', 0)
            ->get()->toArray();
    }

    //销售单实付金额
    static private function getCustomerSellFinalMoney($sellId)
    {
        return SellPayRecordModel::select(
            DB::raw('SUM(expend) as sell_final_pay_money')
        )
        ->whereIn('sell_id', $sellId)
            ->first();
    }

    //销售单套餐总件数
    static private function getCustomerSellPackageAmountInfo($sellId)
    {
        return SellPackageDetailModel::select(
            DB::raw('SUM(num) as sell_package_total_num')
        )
            ->whereIn('sell_id', $sellId)
            ->first();
    }

    //销售单商品总件数
    static private function getCustomerSellMaterielAmountInfo($sellId)
    {
        return SellGoodsDetailModel::select(
            DB::raw('SUM(num) as sell_materiel_total_num')
        )
            ->whereIn('sell_id', $sellId)
            ->first();
    }

    //销售单总销售金额
    static private function getCustomerSellMoney($sellId)
    {
        return SellModel::select(
            DB::raw('SUM(final_money) as total_final_money')
        )
            ->whereIn('id', $sellId)
            ->first();
    }

    //获取所有销售单id信息
    static private function getCustomerSellId($data, $condition, $cond)
    {
        return SellModel::select(
            'id',
        )
            ->where($condition)
            ->where($cond)
            ->where(function($query) use($data){
                if(!empty($data['keyword'])){
                    $query->where('order_no',$data['keyword']);
                }
            })
            ->where('customer_id', $data['customer_id'])
            ->where('repeal_status', 0)
            ->get()->toArray();
    }

    //获取采购单总金额
    static private function getCustomerMaterielFinalMoney($materielId)
    {
        return MaterielModel::select(
            DB::raw('SUM(final_money) as total_final_money'),
        )
            ->whereIn('id', $materielId)
            ->groupBy('supplier_customer_id')
            ->first();
    }

    //获取采购单内容信息
    static private function getCustomerMaterielContentInfo($materielId) {
        return MaterielContentModel::select(
            'materiel_id',
            DB::raw('SUM(num) as total_materiel_num'),
        )
            ->whereIn('materiel_id', $materielId)
            ->groupBy('materiel_id')
            ->first();
    }

    //获取采购单信息
    static private function getCustomerMaterielId($data, $condition, $cond = [])
    {
        return MaterielModel::select(
            'id',
        )->where($condition)
        ->where($cond)
        ->where(function($query) use($data){
            if(!empty($data['keyword'])){
                $query->where('purchase_no',$data['keyword']);
            }
        })
        ->where('supplier_customer_id', $data['customer_id'])
        ->where('repeal_status', 0)
        ->get()->toArray();
    }

    private static function getMaterielInfo($data, $condition)
    {
        return MaterielContentModel::select(
            DB::raw('SUM(num) as total_materiel_num'),
            DB::raw('SUM(final_money) as total_materiel_money')
        )
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
            ->where($condition)
            ->where('b.supplier_customer_id', $data['customer_id'])
            ->where('b.supplier_name', $data['customer_name'])
            ->where('b.repeal_status', 0)
            ->first();
    }

    //采购商品统计
    static public function statisticsPurchasedGoods($condition, $data,$keyword)
    {

        $amountInfo = MaterielContentModel::select(
            DB::raw('SUM(num) as total_amount'),
            'c.name as customer_name'
        )->from('materiel_content as a')
        ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
        ->leftJoin('supplier_customer as c', 'c.id', '=', 'b.supplier_customer_id')
        ->where('b.repeal_status', 0)
        ->where($condition)
        ->where('b.supplier_customer_id',$data['customer_id'])
        ->where(function($query) {
            $query->orWhere('b.pay_status', '!=', 0);
            $query->orWhere('b.in_storage_status', '!=', 0);
        })
         ->where(function($query) use ($keyword) {
            $query->orWhere('a.materiel_name', 'like', '%'.$keyword.'%');
            $query->orWhere('a.type_name', 'like', '%'.$keyword.'%');
            $query->orWhere('a.materiel_no', 'like', '%'.$keyword.'%');
        })
        ->groupBy('a.main_id')
        ->first();
        $result['customer_name'] = $amountInfo['customer_name']??'';
        $result['total_amount'] = empty($amountInfo)?0:$amountInfo['total_amount'];
        $priceInfo = MaterielContentModel::selectRaw('
        SUM(num * unit_price) as total_price
        ')->from('materiel_content as a')
        ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
        ->where('b.repeal_status', 0)
        ->where($condition)
        ->where('b.supplier_customer_id',$data['customer_id'])
        ->where(function($query) {
            $query->orWhere('b.pay_status', '!=', 0);
            $query->orWhere('b.in_storage_status', '!=', 0);
        })->where(function($query) use ($keyword) {
            $query->orWhere('a.materiel_name', 'like', '%'.$keyword.'%');
            $query->orWhere('a.type_name', 'like', '%'.$keyword.'%');
            $query->orWhere('a.materiel_no', 'like', '%'.$keyword.'%');
        })->groupBy('a.main_id')
        ->first();
        $result['total_price'] = empty($priceInfo)?0:$priceInfo['total_price'];
        $query = MaterielContentModel::select(
            'type_id',
            'materiel_name',
            'type_name',
           /*  'materiel_no', */
            'materiel_img',
            DB::raw('SUM(num * unit_price) as total_unit_price'),
            DB::raw('SUM(num) as num')
            )
            ->from('materiel_content as a')
            ->leftJoin('materiel as b', 'b.id', '=', 'a.materiel_id')
            ->where('b.repeal_status', 0)
            ->where($condition)
            ->where('b.supplier_customer_id',$data['customer_id'])
            ->where(function($query) {
                $query->orWhere('b.pay_status', '!=', 0);
                $query->orWhere('b.in_storage_status', '!=', 0);
            })
            ->where(function($query) use ($keyword) {
                $query->orWhere('a.materiel_name', 'like', '%'.$keyword.'%');
                $query->orWhere('a.type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('a.materiel_no', 'like', '%'.$keyword.'%');
            });
            if(!empty($data['number_sort'])){
                $query->orderBy('num',$data['number_sort']);
            }
            if(!empty($data['price_sort'])){
                $query -> orderBy('total_unit_price',$data['price_sort']);
            }
            $query ->groupBy('type_id');
            if(!isset($data['pageSize'])){
                $result['materiel_content_info'] = !empty($query->get())?$query->get()->toArray():[];
            }else{
                $result['materiel_content_info'] = $query->paginate($data['pageSize'],['*'], '',$data['currentPage']);
            }
            return $result;
    }

    static public function sellGoodsList($condition, $data,$keyword)
    {
        //获取所有销售单id信息
        $getCustomerSellInfo = SellModel::select('id','customer_name')
        ->from('sell as a')
            ->where($condition)
            ->where('customer_id', $data['customer_id'])
            ->where('repeal_status', 0)
            ->where('delete_flag', 0)
            ->where(function($query) {
                $query->orWhere('out_status', '!=', 0);
                $query->orWhere('pay_status', '!=', 0);
            })->get();

        $sellId = [];
        foreach($getCustomerSellInfo as $val) {
            $sellId[] = $val['id'];
        }
        if(empty($sellId)) {
            $result['sell_final_money'] = 0;
        }else {
            //销售单总销售金额
            $result = SellModel::select(DB::raw('SUM(final_money) as sell_final_money'))
            ->whereIn('id', $sellId);
            $result = !empty($result->first()) ? $result->first()->toArray():[];
        }
       $query = SellGoodsListModel::select(
            'b.materiel_name',
            'b.type_name',
            'b.materiel_img',
            DB::raw('SUM(num) as total_num'),
            DB::raw('SUM(price * num) as cost_price')//销售总价
            )
            ->from('sell_goods_detail as a')
            ->leftJoin('materiel_type as b', 'b.id', '=', 'a.materiel_type_id')
            //->where($condition)
            ->whereIn('a.sell_id',$sellId)
            ->where(function($query) use ($keyword) {
                $query->orWhere('b.materiel_name', 'like', '%'.$keyword.'%');
                $query->orWhere('b.type_name', 'like', '%'.$keyword.'%');
            });
            if(!empty($data['number_sort'])){
                $query->orderBy('total_num',$data['number_sort']);
            }
            if(!empty($data['price_sort'])){//销售总价
                $query ->orderBy('price',$data['price_sort']);
            }
            $query->groupBy('a.materiel_type_id');
            if(!isset($data['pageSize'])){
                $result['customer_name'] = $getCustomerSellInfo[0]['customer_name'] ?? '';
                $result['sell_goods_list'] = !empty($query->get())?$query->get()->toArray():[];
                if(empty($result['sell_goods_list'])){
                    $result['sell_final_money'] = 0;
                }
                return $result;
            }
             $result['sell_goods_list'] = $query->paginate($data['pageSize'],['*'], '',$data['currentPage']);
       /*  var_dump(DB::getQueryLog());die; */
            if(empty($result['sell_goods_list']['data'])){
                $result['sell_final_money'] = 0;
            }
             return $result;

    }

    //实付金额-销售
    static private function customerSellGoodsList($sellId)
    {
        return SellModel::select(
            'customer_id',
            'customer_name',
            DB::raw('SUM(num) as total_num')
        )
            ->from('sell as a')
            ->leftJoin('sell_goods_detail as b', 'a.id', '=', 'b.sell_id')
            ->where('b.repeal_status', 0)
            ->whereIn('a.id', $sellId)
            ->groupBy('customer_id')
            ->groupBy('customer_name')
            ->get()->toArray();
    }

    static private function customerMaterielGoodsList($materielId)
    {
        return SellModel::select(
            'supplier_customer_id as customer_id',
            'supplier_name as customer_name',
            DB::raw('SUM(num) as total_num')
        )
            ->from('materiel as a')
            ->leftJoin('materiel_content as b', 'a.id', '=', 'b.materiel_id')
            ->where('b.repeal_status', 0)
            ->whereIn('a.id', $materielId)
            ->groupBy('customer_id')
            ->groupBy('customer_name')
            ->get()->toArray();
    }

    /**
     *已售商品统计-客户购买详情列表
     * Author: zlf
     * Created at 2023/12/29 9:36
     * @param $condition
     * @param $data
     * @return array
     */
    static public function sellGoodsBuyCustomerList($condition, $data)
    {
        $query = LogOutStorageModel::select(
            'd.materiel_name',
            'c.compony_name',
            'c.name',
            'a.operate_num',
            'c.id as supplier_customer_id'
        )->from('log_outstorage as a')
        ->leftJoin('sell as b','b.id','=','a.all_id')
        ->leftJoin('supplier_customer as c','c.id','=','b.customer_id')
        ->leftJoin('materiel_type as d','d.id','=','a.materiel_type_id')
        ->where(function($query) use ($data){
            if(!empty($data['keyword'])){
                $query->orWhere('b.customer_name','like','%'.$data['keyword'].'%');
                $query->orWhere('c.phone','like','%'.$data['keyword'].'%');
                $query->orWhere('c.compony_name','like','%'.$data['keyword'].'%');
                $query->orWhere('c.address','like','%'.$data['keyword'].'%');
            }
        })->where($condition)
        ->where([
            'a.materiel_type_id' => $data['sell_goods_id'],
            'a.all_id_type' => 2,
            'a.type' => 0,
            'a.main_id' => $data['main_id'],
            'a.is_cancel' => 0,
            'b.repeal_status' => 0,
        ])->orderBy('a.created_at','DESC')
        ->get()->toArray();

        $arr = [];
        $totalNum = 0 ;
        $goodsData = [];
        if(!empty($query)){
            $componyArr = array_unique(array_column($query, 'compony_name'));
            foreach ($componyArr as $fKey => $fVal){
                $arr[$fKey]['compony_name'] = $fVal;
                $subtotalNum = 0;
                foreach ($query as $sVal){
                    if($fVal == $sVal['compony_name']){
                        $arr[$fKey]['name_list'][] = [
                            'customer_name'=>$sVal['name'],
                            'num' =>$sVal['operate_num']
                        ];
                        $subtotalNum += $sVal['operate_num'];
                    }
                }
                $arr[$fKey]['compony_subtotal'] = $subtotalNum;
                $totalNum += $subtotalNum;
            }

            if(!empty($data['company_initial_sort'])){//数量排序
                $paramSort = array_column($arr,'compony_name');
                $sort = $data['company_initial_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$arr);
            }

            if(!empty($data['compony_subtotal_sort'])){//字母排序
                $paramSort = array_column($arr,'compony_subtotal');
                $sort = $data['compony_subtotal_sort']=='desc'?SORT_DESC:SORT_ASC;
                array_multisort($paramSort,$sort,$arr);
            }
            if(!isset($data['currentPage'])) {
                $goodsData = [
                    'goods_name' => $query[0]['materiel_name'],
                    'total_num' => $totalNum,
                    'list' =>$arr
                ];
            }
        }
        if(!isset($data['currentPage'])) return $goodsData;
        $currentPage = $data['currentPage'];
        $result = array_slice(array_values($arr), --$data['currentPage'] * $data['pageSize'], $data['pageSize']);
        return [
            'goods_name' => $query[0]['materiel_name']??'',
            'total_num' =>$totalNum,
            'total' => count($arr),
            'current_page' => $currentPage,
            'next_page_url' => count($result) < $data['pageSize']?null:config('app.url')."sell_goods_buy_customer?=".($data['currentPage']+1),
            'prev_page_url' => $currentPage==1?null:config('app.url')."sell_goods_buy_customer?=".($currentPage-1),
            "path" => config('app.url')."sell_goods_buy_customer",
            "to" => $currentPage * $data['pageSize'],
            'data' => array_values($result),
            "per_page" => $data['pageSize']
        ];
    }

}
